package com.tyx.modules.manage.service.impl;

import com.tyx.common.exception.ErrorEnum;
import com.tyx.common.exception.ServiceException;
import com.tyx.modules.manage.entity.PractitionersEntity;
import com.tyx.modules.manage.entity.UserOperationEntity;
import com.tyx.modules.manage.service.PractitionersService;
import com.tyx.modules.manage.service.UserOperationService;
import com.tyx.modules.sys.entity.SysUserEntity;
import com.tyx.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tyx.common.utils.PageUtils;
import com.tyx.common.utils.Query;

import com.tyx.modules.manage.dao.OperationDao;
import com.tyx.modules.manage.entity.OperationEntity;
import com.tyx.modules.manage.service.OperationService;
import org.springframework.transaction.annotation.Transactional;


@Service("operationService")
public class OperationServiceImpl extends ServiceImpl<OperationDao, OperationEntity> implements OperationService {

    @Autowired
    UserOperationService userOperationService;
    @Autowired
    SysUserService sysUserService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OperationEntity> page = this.page(
                new Query<OperationEntity>().getPage(params),
                new QueryWrapper<OperationEntity>().orderByAsc("state")
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void stopUsing(Long opId,Long userId) throws ServiceException {
        OperationEntity operationEntity = this.getOne(new QueryWrapper<OperationEntity>().eq("id",opId));
        if(operationEntity == null){
            throw new ServiceException(ErrorEnum.INFOEMPTY);
        }
        if(operationEntity.getState() == 2){
            throw new ServiceException(ErrorEnum.STOPUSING);
        }
        operationEntity.setUpdateTime(new Date());
        operationEntity.setUpdateUser(userId);
        operationEntity.setState(2);
        this.updateById(operationEntity);
        List<UserOperationEntity> list = userOperationService.list(new QueryWrapper<UserOperationEntity>().eq("operation_id",opId));
        List<Long> ids = new ArrayList<>();
        for (UserOperationEntity user : list){
            ids.add(user.getUserId());
        }
        List<SysUserEntity> userList = sysUserService.list(new QueryWrapper<SysUserEntity>().in("user_id",ids));
        for (SysUserEntity user : userList){
            user.setStatus(0);
            sysUserService.updateById(user);
        }
    }

}
